package com.telegram.bz.bots;

import com.alibaba.fastjson.JSON;
import com.code.enums.RewardKeyEnum;
import com.code.models.robot.RobotTaskCheck;
import com.telegram.bz.managers.HttpManager;
import com.telegram.bz.models.ChatMemberGroup;
import com.telegram.bz.models.RobotChat;
import com.telegram.bz.services.*;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.CollectionUtils;
import org.telegram.telegrambots.bots.TelegramLongPollingBot;
import org.telegram.telegrambots.meta.api.objects.*;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 加群机器人
 *
 * @author xiaoyaowang
 */
public class JoinGroupCollectPictureBot extends TelegramLongPollingBot {

    private static Logger logger = LoggerFactory.getLogger(JoinGroupCollectPictureBot.class);

    private String robotName;

    private String robotToken;

    private String listenJoinGroupUrlPrefix;

    private String listenJoinGroupName;

    private RobotChatService robotChatService;

    private RobotSystemService robotSystemService;

    private ChatMemberGroupService chatMemberGroupService;

    private HttpManager httpManager;

    private RobotTaskCheckService robotTaskCheckService;

    private ChatBanService chatBanService;

    private RobotTaskService robotTaskService;

    private String uploadUrl;

    private String uploadPath;

    public void setRobotName(String robotName) {
        this.robotName = robotName;
    }

    public void setRobotToken(String robotToken) {
        this.robotToken = robotToken;
    }

    public void setListenJoinGroupUrlPrefix(String listenJoinGroupUrlPrefix) {
        this.listenJoinGroupUrlPrefix = listenJoinGroupUrlPrefix;
    }

    public void setListenJoinGroupName(String listenJoinGroupName) {
        this.listenJoinGroupName = listenJoinGroupName;
    }

    public void setRobotChatService(RobotChatService robotChatService) {
        this.robotChatService = robotChatService;
    }

    public void setRobotSystemService(RobotSystemService robotSystemService) {
        this.robotSystemService = robotSystemService;
    }

    public void setChatMemberGroupService(ChatMemberGroupService chatMemberGroupService) {
        this.chatMemberGroupService = chatMemberGroupService;
    }

    public void setHttpManager(HttpManager httpManager) {
        this.httpManager = httpManager;
    }

    public void setRobotTaskCheckService(RobotTaskCheckService robotTaskCheckService) {
        this.robotTaskCheckService = robotTaskCheckService;
    }

    public void setChatBanService(ChatBanService chatBanService) {
        this.chatBanService = chatBanService;
    }

    public void setRobotTaskService(RobotTaskService robotTaskService) {
        this.robotTaskService = robotTaskService;
    }

    public void setUploadUrl(String uploadUrl) {
        this.uploadUrl = uploadUrl;
    }

    public void setUploadPath(String uploadPath) {
        this.uploadPath = uploadPath;
    }

    @Override
    public String getBotUsername() {
        return robotName;
    }

    @Override
    public String getBotToken() {
        return robotToken;
    }

    @Override
    public void onUpdateReceived(Update update) {
        logger.info("listen join group bot start work,execute onUpdateReceived method，update:{}", JSON.toJSONString(update));
        try {
            if (update.hasMessage()) {
                Message messageText = update.getMessage();
                if (null != messageText) {
                    Long chatIdLong = messageText.getChatId();
                    if (null != chatIdLong) {
                        String chatId = chatIdLong.toString();
                        // 插入用户或者群组与机器人的绑定关系
                        RobotChat robotChat = new RobotChat();
                        robotChat.setChatId(chatId);
                        robotChat.setRobotName(robotName);
                        robotChatService.insertRobotChat(robotChat);
                        // 保存加群记录
                        String stopRobot = robotSystemService.getSystemValueBySystemKey(RewardKeyEnum.STOP_ROBOT.name());
                        if ("1".equals(stopRobot)) {
                            return;
                        }
                        Chat chat = messageText.getChat();
                        String userName = chat.getUserName();
                        String groupUrl = null;
                        if (!StringUtils.isBlank(userName)) {
                            groupUrl = listenJoinGroupUrlPrefix + userName;
                        }
                        String joinGroupUrl = listenJoinGroupUrlPrefix + listenJoinGroupName;
                        if (!joinGroupUrl.equals(groupUrl)) {
                            return;
                        }
                        List<User> newChatMembers = messageText.getNewChatMembers();
                        logger.info("new chat members:{}", JSON.toJSONString(newChatMembers));
                        List<ChatMemberGroup> chatMemberGroupList = null;
                        if (!CollectionUtils.isEmpty(newChatMembers)) {
                            chatMemberGroupList = new ArrayList<>(newChatMembers.size());
                            Boolean isBot;
                            ChatMemberGroup chatMemberGroup;
                            String newChatId;
                            for (User newChatMember : newChatMembers) {
                                chatMemberGroup = new ChatMemberGroup();
                                chatMemberGroup.setGroupUrl(groupUrl);
                                newChatId = String.valueOf(newChatMember.getId());
                                chatMemberGroup.setChatId(newChatId);
                                if (!chatMemberGroupService.judgeUserWhetherJoinGroup(chatMemberGroup)) {
                                    chatMemberGroup.setGroupName(chat.getTitle());
                                    chatMemberGroup.setUserName(newChatMember.getUserName());
                                    chatMemberGroup.setFirstName(newChatMember.getFirstName());
                                    chatMemberGroup.setLastName(newChatMember.getLastName());
                                    isBot = newChatMember.getIsBot();
                                    if (isBot) {
                                        chatMemberGroup.setIsBot(1);
                                    } else {
                                        chatMemberGroup.setIsBot(0);
                                    }
                                    chatMemberGroup.setDeleted(0);
                                    chatMemberGroup.setCreatedAt(new Date());
                                    chatMemberGroup.setUpdatedAt(new Date());
                                    chatMemberGroupList.add(chatMemberGroup);
                                }

                            }
                        } else {
                            if ("0".equals(robotSystemService.getSystemValueBySystemKey(RewardKeyEnum.SCAN_JOIN_GROUP.name()))) {
                                return;
                            }
                            User from = messageText.getFrom();
                            logger.info("from User:{}", JSON.toJSONString(from));
                            if (null != from) {
                                chatMemberGroupList = new ArrayList<>(1 << 2);
                                ChatMemberGroup chatMemberGroup = new ChatMemberGroup();
                                chatMemberGroup.setGroupUrl(groupUrl);
                                String fromChatId = String.valueOf(from.getId());
                                chatMemberGroup.setChatId(fromChatId);
                                if (!chatMemberGroupService.judgeUserWhetherJoinGroup(chatMemberGroup)) {
                                    chatMemberGroup.setGroupName(chat.getTitle());
                                    chatMemberGroup.setUserName(from.getUserName());
                                    chatMemberGroup.setFirstName(from.getFirstName());
                                    chatMemberGroup.setLastName(from.getLastName());
                                    boolean isBot = from.getIsBot();
                                    if (isBot) {
                                        chatMemberGroup.setIsBot(1);
                                    } else {
                                        chatMemberGroup.setIsBot(0);
                                    }
                                    chatMemberGroup.setDeleted(0);
                                    chatMemberGroup.setCreatedAt(new Date());
                                    chatMemberGroup.setUpdatedAt(new Date());
                                    chatMemberGroupList.add(chatMemberGroup);
                                }
                            }
                        }
                        if (!CollectionUtils.isEmpty(chatMemberGroupList)) {
                            chatMemberGroupService.insertChatMemberGroupList(chatMemberGroupList);
                        }
                        collectPicture(messageText);
                    }
                }

            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("onUpdateReceived error:", e);
        }


    }

    /**
     * 收集审核图片
     */
    private void collectPicture(Message messageText) throws Exception {
        logger.info("开始收集图片");
        // 获取发送方信息
        User fromUser = messageText.getFrom();
        if (null != fromUser) {
            Long userId = fromUser.getId();
            if (null != userId) {
                String fromUserChatId = String.valueOf(userId);
                if (robotTaskCheckService.whetherBanedByChatId(fromUserChatId)
                        || chatBanService.whetherExistChatBanByChatId(fromUserChatId)) {
                    return;
                }
                // 是否完成5个任务
                if (robotTaskService.getTotalFinishTasks(fromUserChatId) != 5) {
                    return;
                }
                List<PhotoSize> photoSizeList = messageText.getPhoto();
                String fileId = null;
                if (!CollectionUtils.isEmpty(photoSizeList)) {
                    logger.info("用户发送的审核截图是缩略图");
                    // 提醒用户重发非缩略图
                    httpManager.sendReSendPhoto(messageText.getChatId(), messageText);
                } else {
                    Document document = messageText.getDocument();
                    if (null != document) {
                        logger.info("用户发送的审核截图不是缩略图");
                        String mimeType = document.getMimeType();
                        if ("video/mp4".equalsIgnoreCase(mimeType)) {
                            return;
                        }
                        fileId = document.getFileId();
                    }
                }
                if (!StringUtils.isBlank(fileId)) {
                    String picUrl = httpManager.getFilePath(robotToken, fileId);
                    if (!StringUtils.isBlank(picUrl)) {
                        picUrl = download(picUrl, uploadUrl, uploadPath);
                    }
                    RobotTaskCheck robotTaskCheck = new RobotTaskCheck();
                    robotTaskCheck.setPicUrl(picUrl);
                    robotTaskCheck.setSendText(picUrl);
                    robotTaskCheck.setState(0);
                    robotTaskCheck.setChatId(fromUserChatId);
                    robotTaskCheckService.insertRobotTaskCheck(robotTaskCheck);
                }
            }
        }
    }

    /**
     * 下载图片到本地目录
     *
     * @param urlString  图片地址
     * @param uploadUrl  保存地址
     * @param uploadPath 保存路径
     */
    private static String download(String urlString, String uploadUrl, String uploadPath) {
        InputStream is = null;
        OutputStream os = null;
        try {
            // 构造URL
            URL url = new URL(urlString);
            // 打开连接
            URLConnection con = url.openConnection();
            //设置请求超时为5s
            con.setConnectTimeout(5 * 1000);
            // 输入流
            is = con.getInputStream();

            // 1K的数据缓冲
            byte[] bs = new byte[1024];
            // 读取到的数据长度
            int len;
            // 输出的文件流
            java.io.File sf = new java.io.File(uploadPath);
            if (!sf.exists()) {
                sf.mkdirs();
            }
            // 新的图片文件名 = 编号 +"."图片扩展名
            String newFileName = urlString.substring(urlString.lastIndexOf("/") + 1);
            String uploadTargetPath = sf.getPath() + "/" + newFileName;
            os = new FileOutputStream(uploadTargetPath);
            // 开始读取
            while ((len = is.read(bs)) != -1) {
                os.write(bs, 0, len);
            }
            return uploadUrl + "/" + newFileName;
        } catch (IOException e) {
            logger.error("download picture error:", e);
        } finally {
            // 完毕，关闭所有链接
            try {
                if (null != os) {
                    os.close();
                }
                if (null != is) {
                    is.close();
                }
            } catch (Exception e) {
                logger.error("io close error:", e);
            }
        }
        return null;
    }
}
